/**
 * @author zulianp@lu.unisi.ch & remo.lemma@lu.unisi.ch
 */

package ch.unisi.inf.projects.java.uom.gui.commands;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;

import ch.unisi.inf.projects.java.uom.Database;
import ch.unisi.inf.projects.java.uom.elements.ItemManager;

public final class CreateDatabaseCommand extends Command {
    private static final long serialVersionUID = -1L;
    
    public CreateDatabaseCommand ()
    {
        putValue(NAME,"Create Database");
        putValue(SHORT_DESCRIPTION,"Creates a new database");
        putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    }
    
	public void actionPerformed (final ActionEvent ev)
	{
		final JFileChooser fileChooser = new JFileChooser();
		fileChooser.setCurrentDirectory(new File("."));
		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		fileChooser.setAcceptAllFileFilterUsed(false);
		fileChooser.setDialogTitle("Select a database");
		fileChooser.setFileFilter(new FileFilter() {
			public boolean accept (final File f) {
				return false;
			}
			public String getDescription () { return "Create new directory"; }
		});
		if (fileChooser.showDialog(null, "Create Database") == JFileChooser.APPROVE_OPTION)
		{
			final String dbName = fileChooser.getSelectedFile().getAbsolutePath();
			if (new File(dbName).exists()) {
				JOptionPane.showMessageDialog(null, "Cannot overwrite existsing file!", "File already exists", JOptionPane.ERROR_MESSAGE);
				return;
			}
			Database.init(dbName,true);
			try {
				final Database db = Database.instance();
				db.connect();
				ItemManager.instance().databaseHasOpened();
			}
			catch (final Exception ex) {
				ex.printStackTrace();
				JOptionPane.showMessageDialog(null, ex.getMessage(), "Database creation error", JOptionPane.ERROR_MESSAGE);
			}
			
		}
	}
}
